package main

import (
	"log"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/resphelper"
	"yundian/internel/app/models/prices"
)

func main()  {
	ruleInfo := &prices.PriceModel{
		Id:               0,
		ProductId:        "",
		DeviceTypeId:     10,
		PlaceId:          0,
		UseDuration:      0,
		PayMoney:         0,
		SetMealNum:       0,
		Status:           0,
		RuleName:         "",
		IsRecommend:      0,
		Priority:         0,
		Deposit:          1000,
		BaseTimes:        60,
		BasePrice:        200,
		PayInterval:      60,
		PayIntervalPrice: 200,
		FreeTimes:        5,
		MaxTime:          1440,
		MaxPayPrice:      1000,
		PayTactics:       0,
		Name:             "",
		CreateAt:         0,
	}
	// 1小时 3600
	GetOrderSettMoney(180, 0, ruleInfo, 1)
}

// useTime 时间戳到秒
func GetOrderSettMoney(useTime, payMoney int64, ruleInfo *prices.PriceModel, payFrom int8) (settResult *resphelper.SettlementResp) {
	var settMoney, returnMoney, useTimeHour int64
	if ruleInfo.FreeTimes > 0 && ruleInfo.FreeTimes < 15 { // 有设置免费时长的 15分钟以内的算法
		if useTime <= int64(ruleInfo.FreeTimes)*60 { // 免费时长内,免费使用
			settMoney = 0
			returnMoney = 0
		} else { // 超出免费时长,计算价格
			useTime = useTime - int64(ruleInfo.FreeTimes)*60
			h := int64(ruleInfo.BaseTimes / ruleInfo.PayInterval)
			useTimeHour = helper.UseTimeToHour(useTime, int64(ruleInfo.PayInterval))
			if useTimeHour <= h {
				settMoney = ruleInfo.BasePrice // 最低使用价格
			} else {
				// 最低使用价格 + 每小时价格
				settMoney = ruleInfo.BasePrice + (useTimeHour-h)*ruleInfo.PayIntervalPrice
			}
			returnMoney = payMoney - settMoney // 退还金额 (订单支付金额 - 结算金额)
		}
	} else if ruleInfo.FreeTimes >= 15 { // 有免费时长 15分钟以上的算法
		if useTime <= int64(ruleInfo.FreeTimes)*60 { // 免费时长内,免费使用
			settMoney = 0
			returnMoney = 0
		} else {
			useTime = useTime - int64(ruleInfo.FreeTimes)*60
			useTimeHour = helper.UseTimeToHour(useTime, int64(ruleInfo.PayInterval))
			settMoney = useTimeHour * ruleInfo.PayIntervalPrice // 结算金额
			returnMoney = payMoney - settMoney
		}
	} else { // 没有免费时长，使用最低使用时长
		h := int64(ruleInfo.BaseTimes / ruleInfo.PayInterval)
		useTimeHour = helper.UseTimeToHour(useTime, int64(ruleInfo.PayInterval))
		if useTimeHour <= h {
			settMoney = ruleInfo.BasePrice // 最低使用价格
		} else {
			// 最低使用价格 + 每小时价格
			settMoney = ruleInfo.BasePrice + (useTimeHour-h)*ruleInfo.PayIntervalPrice
		}
		returnMoney = payMoney - settMoney // 退还金额 (订单支付金额 - 结算金额)
	}

	log.Println("使用时长", useTime, useTimeHour, "结算金额", settMoney, "支付金额", payMoney)
	if payFrom == 1 { // 免押，支付金额为0
		returnMoney = 0
	}

	if useTime > int64(ruleInfo.MaxTime*60) { // 使用时长大于最大时长时
		settMoney = ruleInfo.MaxPayPrice
		returnMoney = 0
	}

	if settMoney > ruleInfo.MaxPayPrice { // 结算金额大于封顶金额（最大金额）
		settMoney = ruleInfo.MaxPayPrice
		returnMoney = 0
	}

	settResult = &resphelper.SettlementResp{
		UseTime:     useTime,
		SettMoney:   settMoney,
		ReturnMoney: returnMoney,
	}

	return settResult
}
